<template>
    <el-scrollbar v-loading="loading" class="group-box">
        <el-tree
            ref="groupTreeRef"
            class="unity-kit-group-tree"
            :data="groupData"
            :props="defaultProps"
            :default-expand-all="true"
            :expand-on-click-node="false"
            highlight-current
            node-key="id"
            @node-click="chooseGroup">
            <template #default="{ node }">
                <el-tooltip
                    class="box-item"
                    :disabled="disabled"
                    :content="`${node.label}(${node.data?.nums || 0})`"
                    placement="top-start">
                    <span class="grouping_tooltip_label" @mouseenter="handleMouse($event)">
                        {{ node.label }}({{ node.data?.nums || 0 }})
                    </span>
                </el-tooltip>
            </template>
        </el-tree>
    </el-scrollbar>
</template>

<script setup lang="ts">
import { ElTree } from 'element-plus';
import { withDefaults, ref, watch, computed, nextTick } from 'vue';
import { isTextBeyond } from '../../utils/index';

interface Props {
    modelValue?: any;
    loading?: boolean;
    groupData?: any;
}

const props = withDefaults(defineProps<Props>(), {
    modelValue: '',
    loading: false,
    groupData: []
});

const groupTreeRef = ref();

const emit = defineEmits(['update:modelValue', 'submit']);

const groupId = computed({
    get() {
        return props.modelValue;
    },
    set(val) {
        emit('update:modelValue', val);
    }
});

const defaultProps = {
    checkStrictly: true,
    emitPath: false,
    children: 'children',
    label: 'name',
    value: 'id'
};

const disabled = ref(true);
const handleMouse = e => {
    disabled.value = isTextBeyond(e);
};

const chooseGroup = value => {
    groupTreeRef.value.setCurrentKey(value.id);
    emit('submit', value);
};

watch(
    () => props.groupData,
    val => {
        nextTick(() => groupTreeRef.value.setCurrentKey(groupId.value));
    }
);
</script>

<style lang="scss" scoped>
.unity-kit-group-tree {
    margin-top: 10px;

    :deep(.el-tree-node__expand-icon) {
        color: #ff6b00;
    }

    :deep(.el-tree-node) {
        &.is-current {
            > .el-tree-node__content {
                background: #fff1e8;
            }
        }

        .el-tree-node__content {
            width: 170px;

            &.is-focusable {
                background: #fffaf9;
            }

            &:hover {
                background: #fffaf9;
            }
        }

        .el-tree-node__expand-icon.is-leaf {
            color: transparent;
        }
    }

    .grouping_tooltip_label {
        width: 120px;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }
}

.group-box {
    box-sizing: border-box;
    width: 170px;
    height: 514px;
    background: #fff;
}
</style>
